<template>
  <div id="basic-info">
    <el-button style="line-height:25px;"
               @click="$router.go(-1)"
               icon="el-icon-back"
               type="text">返回</el-button>

    <h3>演出新增/编辑</h3>
    <main>
      <el-form label-width="100px"
               style="overflow: hidden;">
        <el-form-item label="演出名称"
                      class="form-item">
          <el-input v-model="addObj.name"></el-input>
        </el-form-item>
        <el-form-item label="演出类型"
                      class="form-item">
          <el-select v-model="addObj.typeCode"
                     filterable
                     default-first-option
                     style="width:100%">
            <el-option label="综合"
                       :value="1"></el-option>
            <el-option label="春节团拜会"
                       :value="2"></el-option>
            <el-option label="新年茶话会"
                       :value="3"></el-option>
            <el-option label="新年戏曲晚会"
                       :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结构类型"
                      class="form-item">
          <el-select v-model="addObj.category"
                     :disabled="id!==''"
                     style="width:100%">
            <el-option label="节目型"
                       :value="1"></el-option>
            <el-option label="篇章型"
                       :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-item"
                      label="演出地点">
          <el-input v-model="addObj.address"></el-input>
        </el-form-item>
        <el-form-item class="form-item"
                      label="演出时间">
          <el-date-picker style="width:100%"
                          type="datetime"
                          v-model="addObj.time"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="form-item"
                      label="演出时长">
          <el-input v-model.number="addObj.lenth"
                    maxlength="3"
                    oninput="if(isNaN(parseInt(value)))value=value.slice(0,0)"
                    placeholder="请输入整数分钟">
            <i slot="suffix">分钟</i>
          </el-input>
        </el-form-item>
        <div v-if="extraArray.length === 0"
                style="margin-bottom:22px;text-align: center;">
          <el-button icon="el-icon-plus"
                     @click="addItem">
          </el-button>
        </div>

        <div style="width:100%;margin-bottom:22px;display:flex;align-items:center;justify-content: space-between;"
             v-for="(item,i) in extraArray"
             :key="item.id">
          <!-- <el-input style="width:80px;"
                  v-model="item.key"></el-input> -->
          <el-select style="width:120px;"
                     allow-create
                     filterable
                     default-first-option
                     v-model="item.key">
            <el-option label="指导思想"
                       value="指导思想"></el-option>
            <el-option label="演出主题"
                       value="演出主题"></el-option>
            <el-option label="艺术特点"
                       value="艺术特点"></el-option>
            <el-option label="简介"
                       value="简介"></el-option>

          </el-select>
          <el-input style="width:calc(100% - 240px)"
                    type="textarea"
                    :autosize="{ minRows: 5, maxRows: 5 }"
                    v-model="item.value"></el-input>
          <el-button-group style="width:112px">
            <el-button icon="el-icon-plus"
                       v-if="i === extraArray.length-1"
                       @click="addItem"></el-button>
            <el-button icon="el-icon-minus"
                       @click="deleteItem(i)"></el-button>
          </el-button-group>
        </div>
        <el-form-item style="width:100%"
                      class="form-item"
                      label="上传视频">
          <div class="url-item"
               v-if="addObj.videoUrl">
            <el-link target="在线播放"
                     :href="addObj.videoUrl">{{addObj.videoUrl}}</el-link>
            <el-button type="text"
                       size="small"
                       @click="addObj.videoUrl = ''"
                       style="color:red;margin-left:10px;">删除</el-button>
          </div>
          <el-upload class="avatar-uploader"
                     action=""
                     :http-request="beginUpload"
                     :show-file-list="false">
            <!-- <img v-if="imageUrl"
               :src="imageUrl"
               class="avatar"> -->
            <!-- <i v-if="!imageUrl"
             class="el-icon-plus avatar-uploader-icon" /> -->
            <el-button type="text"
                       icon="el-icon-upload">上传</el-button>
          </el-upload>
          <el-progress style="width:90%"
                       :status="uploadStatus"
                       :percentage="Number(percentage.toFixed(2))"></el-progress>
          <!-- <el-button @click="pauseUpload"
                   size="mini">暂停</el-button>
        <el-button @click="goonUpload"
                   size="mini">继续</el-button> -->
        </el-form-item>
        <el-form-item label="节目单"
                      class="form-item"
                      style="width:100%">
          <div>
            <el-upload action=""
                       list-type="picture-card"
                       :limit="10"
                       :http-request="beginUploadPic"
                       :on-preview="handlePreview"
                       :file-list="fileListPic"
                       :before-upload="beforeAvatarUpload"
                       :on-remove="handleRemovePic">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>

      </el-form>
    </main>
    <footer style="text-align:center;padding-bottom:25px">
      <el-button type="primary"
                 :loading="btnLoading"
                 size="medium"
                 @click="submit">保存并返回</el-button>
    </footer>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%"
           :src="dialogImageUrl"
           alt="">
    </el-dialog>
  </div>
</template>

<script>
import API from '../../api/show'
import OSS from 'ali-oss'
import axios from 'axios'

export default {
  name: 'BasicAdd',
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      fileListPic: [],
      imageUrl: '',
      percentage: 0,
      checkpoint: null,
      client: null,
      filename: '',
      ossObj: null,
      uploadStatus: undefined,
      pause: false,
      imgsBill: [],

      fileList: [
        // {
        //   name: 'food.jpeg',
        //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        // },
        {
          name: 'food2.mp4',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        }
      ],
      id: '',
      btnLoading: false,
      addObj: {
        type: '',
        name: '',
        address: '',
        aside: '',
        mainSense: '',
        features: '',
        category: 1,
        videoOriginName: null,
        videoNewName: null,
        imgsBill: []
      },
      extraArray: [
        {
          id: this.guid(),
          key: '',
          value: ''
        }
      ]
    }
  },
  created() {

    // this.client = new OSS({
    //   region: 'oss-cn-hangzhou',
    //   accessKeyId: '<Your AccessKeyId>',
    //   accessKeySecret: '<Your AccessKeySecret>',
    //   bucket: 'Your bucket name',
    //   secure: false
    // })
  },
  mounted() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.queryById(this.$route.query.id)
    }
  },
  methods: {
    getToken(filename = 'test.mp4', cb) {
      axios({
        baseURL: process.env.VUE_APP_BASE_API,
        url: '/sts/token',
        method: 'get',
        params: { videoName: filename }
      }).then(res => {
        // console.log('getToken', res.data.data)
        const data = res.data.data
        this.ossObj = res.data.data
        this.addObj.videoNewName = data.videoName
        this.client = new OSS({
          region: data.region,
          accessKeyId: data.accessKeyId,
          accessKeySecret: data.accessKeySecret,
          stsToken: data.securityToken,
          bucket: data.bucket,
          endpoint: 'oss-cn-beijing.aliyuncs.com'
        })
        if (cb) cb(data.videoName)
      })
    },
    async ossUpload(filename, file) {
      // console.log('startUpload...', filename, file)
      const _this = this
      try {
        // debugger
        this.uploadStatus = undefined
        const result = await this.client.multipartUpload(filename, file, {
          progress: async (p, checkpoint) => {
            _this.checkpoint = checkpoint
            _this.percentage = p * 100
          },
          checkpoint: _this.checkpoint
        })
        if (result.res.statusCode !== 200) {
          this.addObj.videoOriginName = null
          this.addObj.videoNewName = null
          this.$message.error('上传失败！')
          this.uploadStatus = 'exception'
        } else if (result.res.statusCode === 200) {
          this.addObj.videoUrl = ''
          this.$message.success('上传成功！')
          this.uploadStatus = 'success'
        } else {
          this.$message.error('上传失败！')
          this.uploadStatus = 'exception'
        }
        this.checkpoint = null
        // console.log(212, result)
      } catch (e) {
        console.log('exception', e)
      }
    },
    beginUpload(file) {
      // console.log('begin', file)
      const filename = file.file.name
      this.addObj.videoOriginName = filename
      this.file = file
      this.filename = filename
      this.getToken(filename, (newName) => {
        // console.log('newName', newName)
        this.ossUpload(newName, file.file)
      })
    },
    pauseUpload() {
      this.client.cancel()
    },
    goonUpload() {
      const file = this.file
      this.ossUpload(this.addObj.videoNewName, file.file)
    },

    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16);
      });
    },
    addItem() {
      const uuid = this.guid()
      this.extraArray.push({ id: uuid, key: '', value: '' })
    },
    deleteItem(i) {
      this.extraArray.splice(i, 1)
    },
    submit() {
      this.btnLoading = true
      const params = { ...this.addObj }
      params.extra = this.extraArray
      if (this.imgsBill && this.imgsBill.length > 0) {
        params.imgsBill = this.imgsBill.map(img => img.name)
      }
      // if (params.type === params.typeCode) params.typeCode = null
      if (!this.id) {
        API.addPlay(params).then(res => {
          this.btnLoading = false
          this.$router.go(-1)
        }).catch(() => {
          this.btnLoading = false
          // this.$router.go(-1)
        })
      } else {
        API.editActor(params).then(res => {
          this.btnLoading = false
          this.$router.go(-1)
        }).catch(() => {
          this.btnLoading = false
          // this.$router.go(-1)
        })
      }
    },
    queryById(id) {
      API.getPlayById(id).then(res => {
        // if (!res.data.typeCode) res.data.typeCode = res.data.type
        if (res.data.extra && res.data.extra.length > 0) {
          this.extraArray = res.data.extra.map(e => {
            return {
              id: e.id || this.guid(),
              key: e.key,
              value: e.value
            }
          })
        } else {
          this.extraArray = res.data.extra || []
        }

        if (res.data.urlList && res.data.urlList.length > 0) {
          this.imgsBill = res.data.urlList.map((r, i) => {
            return {
              name: res.data.imgsBill[i],
              url: r
            }
          })
          this.fileListPic = this.imgsBill
        }

        this.addObj = Object.assign({}, this.addObj, res.data)
      })
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      // console.log(file);
    },
    beginUploadPic(file) {
      // console.log(file)
      this.addObj.originalPhotoName = file.file.name
      const form = new FormData()
      form.append('file', file.file)
      axios.post(process.env.VUE_APP_BASE_API + '/admin/uploadimg', form).then(res => {
        // this.addObj.photoName = res.data.data.imgName
        this.imgsBill.push({ name: res.data.data.imgName, originName: file.file.name })
      }).catch(err => {
        console.log(err)
        this.addObj.photoName = null
        this.addObj.originalPhotoName = null
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type.includes('image');
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error('上传文件只能是图片格式!');
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传文件不能超过 5M!');
        return false
      }
      /* const isSise = new Promise((resolve, reject) => {
        const isLt2M = file.size / 1024 / 1024 < 5;
        const width = 500;
        const height = 300;
        const url = window.URL || window.webkitURL;
        const img = new Image();
        img.onload = () => {
          file.width = img.width;      // 获取到width放在了file属性上
          file.height = img.height;    // 获取到height放在了file属性上
          const valid = isLt2M && img.width >= width && img.height >= height;
          valid ? resolve({ width: img.width, height: img.height }) : reject({ width: img.width, height: img.height });
        };
        img.src = url.createObjectURL(file)
      }).then(() => {
        return file
      }).catch((err) => {
        console.warn(err)
        this.$message.error('图片大小不能超过 5M，图片像素不能低于500*300！');
        return Promise.reject(false)
      })
      console.log(121313, isSise)
      if (!isSise) {
        this.$message.error('图片大小不能超过 5M，图片像素不能低于500*300！');
      }
      return isJPG && isSise */
      return isJPG && isLt5M
    },
    handleRemovePic(file, fileList) {
      this.imgsBill = this.imgsBill.filter(b => {
        return (b.originName !== file.name && b.name !== file.name)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
#basic-info {
  width: 100%;
  padding: 0 30px;
  main {
    width: 900px;
    .form-item {
      width: 50%;
      float: left;
    }
    .url-item {
      line-height: 30px;
      display: flex;
      height: 30px;
      margin-top: 5px;
      align-items: center;
    }
  }
  /deep/ .el-progress-bar {
    padding-right: 80px;
    margin-right: -80px;
  }
}
</style>
